new Vue({
    el: '#app',
    data() {
        return {
            form: {
                value: '',
                PageNumber: 1,
                RowAmount: 20,
            },
            list: [],
            // 仅展示当前订单
            currentOrder: null,
            total: 0,
            // 合同确认弹窗与上下文
            dialogContractVisible: false,
            currentContractRow: null,
            pageSupply: null,
            currentSupplyId: '',
            currentOrderSerial: '',
            // 权限相关：当前企业与来源
            enterpriseId: '',
            fromApplyDetail: false,
            // 付款弹窗与表单
            dialogPayVisible: false,
            paySaving: false,
            payContext: null, // { order, stage }
            payForm: { amount: '', voucherList: [] },
            // 物流发货弹窗与表单
            dialogShipVisible: false,
            shipSaving: false,
            shipContext: null, // { order, stage }
            shipForm: { logisticsCode: '', logisticsNumber: '', deliveryQuantity: '', voucherList: [] },
            logisticsOptions: [],
            shipUnitText: '单位',
            shipDeliveredTotal: 0,
            unitMap: {},
            // 收货详情弹窗
            dialogReceiveVisible: false,
            receiveView: null,
            receiveContext: null, // { order }
            receiveForm: { receiptQuantity: '' },
            receiveLogisticsList: [],
            receiveUnitText: '单位',
            receiveSaving: false,
            // 收款详情弹窗
            dialogReceiptVisible: false,
            receiptContext: null, // { order, stage }
            receiptView: { contractAmount: '', stageDueAmount: '', actualAmount: '', voucherUrl: '' },
            // 收款表单
            receiptForm: { amount: '' },
            
        }
    },
    mounted() {
        this.getList();
    },
        methods: {
            handleBack() {
                // 如果是从“我的采购”详情跳入（带有 applyId），返回时回到我的采购列表
                let applyId = '';
                try { applyId = getQueryObject(window.location.href, 'applyId') || ''; } catch (e) { applyId = ''; }
                if (applyId) {
                    window.location.href = '../supply_order/index.html';
                } else {
                    window.location.href = './index.html';
                }
            },
        // 打开阶段付款弹窗
        openPayDialog(orderRow, stageRow) {
            this.payContext = { order: orderRow, stage: stageRow };
            this.payForm = { amount: '', Picture_URL: '' };
            this.dialogPayVisible = true;
        },
        // 打开发货弹窗
        async openShipDialog(orderRow, stageRow) {
            this.shipContext = { order: orderRow, stage: stageRow };
            this.shipForm = { logisticsCode: '', logisticsNumber: '', deliveryQuantity: '', Picture_URL: '' };
            try {
                const serial = (orderRow && orderRow.Article_Unit_SerialNumber)
                    || (orderRow && orderRow.originSupply && orderRow.originSupply.Article_Unit_SerialNumber)
                    || (this.pageSupply && this.pageSupply.Article_Unit_SerialNumber)
                    || '';
                const txt = this.getUnitText(serial);
                this.shipUnitText = (txt && String(txt).trim()) || '单位';
            } catch (e) { this.shipUnitText = '单位'; }
            // 加载物流公司
            await this.loadLogisticsOptions();
            // 聚合已发货数量
            try {
                const list = await generalApi.generalQueryByTableName({
                    Data: 'supply_order_logistics',
                    Condition: `Supply_Order_SerialNumber='${String(orderRow.Supply_Order_SerialNumber||'').replace(/'/g,"''")}'`
                });
                const arr = Array.isArray(list) ? list : (list.Data || []);
                const sum = (arr || []).reduce((acc, it) => acc + Number(it.Delivery_Quantity || 0), 0);
                this.shipDeliveredTotal = Number.isFinite(sum) ? sum : 0;
            } catch (e) {
                this.shipDeliveredTotal = 0;
            }
            this.dialogShipVisible = true;
        },
        async loadLogisticsOptions() {
            try {
                // 后端接口要求同时传入 Data 和 Condition，即便不筛选也需提供 Condition
                const res = await generalApi.generalQueryByTableName({ Data: 'logistics_info', Condition: '' });
                const arr = Array.isArray(res) ? res : (res.Data || []);
                this.logisticsOptions = (arr || []).map(it => ({
                    Logistics_Code: it.Logistics_Code,
                    Logistics_Name: it.Logistics_Name
                }));
            } catch (e) {
                this.logisticsOptions = [];
                console.error('加载物流公司失败', e);
            }
        },
        
        // 打开收款详情弹窗（展示付款时填的内容）
        async openReceiptDialog(orderRow, stageRow) {
            this.receiptContext = { order: orderRow, stage: stageRow };
            const orderAmount = orderRow && orderRow.Amount ? String(orderRow.Amount) : '';
            const stageDueAmount = (stageRow && stageRow.dueAmount !== undefined && stageRow.dueAmount !== null && stageRow.dueAmount !== '')
                ? String(stageRow.dueAmount) : '';
            let actualAmount = '';
            let voucherUrl = '';
            let stageDueAmountFallback = '';
            try {
                // 优先使用阶段主键查询
                const serial = String(stageRow && stageRow.serial || '').trim();
                const condSafeOrder = String(orderRow.Supply_Order_SerialNumber || '').replace(/'/g, "''");
                const condSafeStage = String(stageRow && stageRow.stage || '').replace(/'/g, "''");
                const cond = serial
                    ? `Supply_Order_Paystages_SerialNumber='${serial.replace(/'/g, "''")}'`
                    : `Supply_Order_SerialNumber='${condSafeOrder}' AND Stage_Name='${condSafeStage}'`;
                const arr = await generalApi.generalQueryByTableName({
                    Data: 'supply_order_paystages',
                    Condition: cond
                });
                let rec = null;
                const list = Array.isArray(arr) ? arr : (arr && Array.isArray(arr.Data) ? arr.Data : []);
                if (list && list.length > 0) rec = list[0];
                if (rec) {
                    actualAmount = rec.Paid_Amount || rec.Payment_Amount || '';
                    const pic = rec.Picture_URL || '';
                    voucherUrl = pic ? (String(pic).startsWith('http') ? pic : ((typeof imageApi !== 'undefined' ? imageApi : '') + pic)) : '';
                    stageDueAmountFallback = rec.Trading_Amount || '';
                }
            } catch (e) {}
            // 若表未查到，尝试用阶段行聚合的 paidAmount
            if (!actualAmount && stageRow && stageRow.paidAmount !== undefined && stageRow.paidAmount !== null && stageRow.paidAmount !== '') {
                actualAmount = String(stageRow.paidAmount);
            }
            this.receiptView = {
                contractAmount: orderAmount,
                stageDueAmount: stageDueAmount || stageDueAmountFallback || '',
                actualAmount: '',
                voucherUrl: voucherUrl
            };
            this.receiptForm = { amount: '' };
            this.dialogReceiptVisible = true;
        },
        // 收款确认：写入收款表和更新“下一阶段”的开始/结束时间
        async onConfirmReceipt() {
            try {
                if (!this.receiptContext || !this.receiptContext.order) { this.dialogReceiptVisible=false; return; }
                const order = this.receiptContext.order;
                const stage = this.receiptContext.stage || {};
                const cond = `Supply_Order_SerialNumber='${String(order.Supply_Order_SerialNumber||'').replace(/'/g,"''")}' AND Stage_Name='${String(stage.stage||'').replace(/'/g,"''")}'`;
                let row = null;
                // 使用阶段主键
                const serialFromUI = String(stage.serial || '').trim();
                if (serialFromUI) {
                    row = { Supply_Order_Paystages_SerialNumber: serialFromUI };
                } else {
                    const arr = await generalApi.generalQueryByTableNameWithOriginal({ Data: 'supply_order_paystages', Condition: cond });
                    row = Array.isArray(arr) ? arr[0] : (arr && arr.Data && arr.Data[0]);
                }

                const now = getYMDHMSDate();
                const creator = $.cookie('user') || $.cookie('enterprise') || '';
                // 验证实际收款金额
                const inputAmount = String(this.receiptForm && this.receiptForm.amount || '').trim();
                if (!inputAmount) {
                    this.$message.error('请输入实际收款金额');
                    return;
                }
                const amountNum = Number(inputAmount);
                if (!Number.isFinite(amountNum) || amountNum <= 0) {
                    this.$message.error('请输入有效的收款金额');
                    return;
                }
                const condSafeOrder = String(order.Supply_Order_SerialNumber || '').replace(/'/g, "''");
                const collectionAmountRaw = (stage && stage.dueAmount !== undefined && stage.dueAmount !== null && stage.dueAmount !== '')
                    ? stage.dueAmount : (this.receiptView && this.receiptView.stageDueAmount || '');
                const collectionAmountNum = Number(collectionAmountRaw || 0);
                const collectionAmount = String(collectionAmountNum);
                const collectionOrderNumber = serialFromUI || (row && row.Supply_Order_Paystages_SerialNumber) || '';
                // 累计已收款金额（查明细聚合）
                let oldCollected = 0;
                try {
                    if (collectionOrderNumber) {
                        const colArr = await generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'collection_detail',
                            Condition: `Collection_Order_Number='${String(collectionOrderNumber).replace(/'/g, "''")}'`
                        });
                        const list = Array.isArray(colArr) ? colArr : (colArr && colArr.Data) || [];
                        oldCollected = (list || []).reduce((sum, it) => {
                            const n = Number(it.Amount || 0);
                            return sum + (Number.isFinite(n) ? n : 0);
                        }, 0);
                    }
                } catch (e) { /* ignore */ }
                const newCollected = accAdd(oldCollected, amountNum);
                if (Number.isFinite(collectionAmountNum) && collectionAmountNum > 0 && newCollected > collectionAmountNum) {
                    this.$message.error('收款金额超出本阶段应收');
                    return;
                }
                const unAmountNum = Math.max(0, Number((collectionAmountNum - newCollected).toFixed(2)));
                const unAmountStr = String(unAmountNum);
                // 若阶段记录存在，提取其凭证图片作为收款凭证
                const voucherPic = (row && row.Picture_URL) ? row.Picture_URL : (
                    (typeof currentStageRow !== 'undefined' && currentStageRow && currentStageRow.Picture_URL) ? currentStageRow.Picture_URL : ''
                );
                // 构建提交数据：新增收款记录；其余更新写入 Modify（主表与阶段表）
                const dataset = { Add: { collection: this.getReceipt(condSafeOrder, collectionAmount, collectionOrderNumber, inputAmount, voucherPic), base_operation_log: [] }, Modify: {} };

                // 1) 累加主表收款并计算剩余未收：Unamount = Amount - Collection_Amount
                try {
                    const ordArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'supply_order',
                        Condition: `Supply_Order_SerialNumber='${condSafeOrder}'`
                    });
                    const ordRow = Array.isArray(ordArr) ? ordArr[0] : (ordArr && ordArr.Data && ordArr.Data[0]);
                    if (ordRow) {
                        const oldOrderCol = Number(ordRow.Collection_Amount || 0);
                        const newOrderCol = accAdd(oldOrderCol, amountNum);
                        const orderAmt = Number(ordRow.Amount || 0);
                        const orderUn = Math.max(0, Number((orderAmt - newOrderCol).toFixed(2)));
                        ordRow.Collection_Amount = String(newOrderCol);
                        ordRow.Unamount = String(orderUn);
                        ordRow.Operation_ID = creator;
                        ordRow.Operation_Datetime = now;
                        dataset.Modify['supply_order'] = [ordRow];
                    }
                } catch (e) { /* ignore */ }

                // 更新当前阶段的收款按钮状态：满额置灰
                try {
                    let currentStageRow = null;
                    if (collectionOrderNumber) {
                        const curArr = await generalApi.generalQueryByTableNameWithOriginal({
                            Data: 'supply_order_paystages',
                            Condition: `Supply_Order_Paystages_SerialNumber='${String(collectionOrderNumber).replace(/'/g, "''")}'`
                        });
                        currentStageRow = Array.isArray(curArr) ? curArr[0] : (curArr && curArr.Data && curArr.Data[0]);
                    }
                    if (!currentStageRow) {
                        const fbArr = await generalApi.generalQueryByTableNameWithOriginal({ Data: 'supply_order_paystages', Condition: cond });
                        currentStageRow = Array.isArray(fbArr) ? fbArr[0] : (fbArr && fbArr.Data && fbArr.Data[0]);
                    }
                    if (currentStageRow) {
                        // 累加阶段收款并计算剩余未收：Unamount = Amount - Collection_Amount（若无 Amount，回退使用 Trading_Amount/Due_Amount）
                        const oldStageCol = Number(currentStageRow.Collection_Amount || 0);
                        const newStageCol = accAdd(oldStageCol, amountNum);
                        const stageBaseAmt = Number(
                            (currentStageRow.Amount !== undefined ? currentStageRow.Amount : (currentStageRow.Trading_Amount !== undefined ? currentStageRow.Trading_Amount : currentStageRow.Due_Amount)) || 0
                        );
                        const stageUn = Math.max(0, Number((stageBaseAmt - newStageCol).toFixed(2)));
                        currentStageRow.Collection_Amount = String(newStageCol);
                        currentStageRow.Unamount = String(stageUn);

                        currentStageRow.Receipt_Pay_Status = (newCollected >= collectionAmountNum && collectionAmountNum > 0) ? '1' : '0';

                        // 若已有阶段修改，合并到同一数组；否则直接设置
                        if (dataset.Modify['supply_order_paystages'] && Array.isArray(dataset.Modify['supply_order_paystages'])) {
                            dataset.Modify['supply_order_paystages'].push(currentStageRow);
                        } else {
                            dataset.Modify['supply_order_paystages'] = [currentStageRow];
                        }
                    }
                } catch (e) { /* ignore */ }

                // 使用已定义的 SQL（supply_payment_stages）按报价阶段号排序，定位“当前阶段的下一阶段”
                let nextStageRow = null;
                try {
                    const sqlArr = await generalApi.generalQueryBySQLSerialNumber({
                        SQLSerialNumber: 'supply_payment_stages',
                        Condition: utf8ToBase64(String(order.Supply_Order_SerialNumber || '')),
                        ExtensionCondition: ''
                    });
                    const rows = Array.isArray(sqlArr) ? sqlArr : [];
                    const curIdx = rows.findIndex(r => String(r.Stage_Name || '').trim() === String(stage.stage || '').trim());
                    if (curIdx >= 0 && curIdx + 1 < rows.length) {
                        const nextLight = rows[curIdx + 1];
                        // 二次查询获取“完整原始行”对象，避免仅联表字段导致保存失败
                        if (nextLight && nextLight.Supply_Order_Paystages_SerialNumber) {
                            try {
                                const nextArr = await generalApi.generalQueryByTableNameWithOriginal({
                                    Data: 'supply_order_paystages',
                                    Condition: `Supply_Order_Paystages_SerialNumber='${String(nextLight.Supply_Order_Paystages_SerialNumber).replace(/'/g,"''")}'`
                                });
                                nextStageRow = Array.isArray(nextArr) ? nextArr[0] : (nextArr && nextArr.Data && nextArr.Data[0]);
                            } catch (e2) { /* ignore */ }
                            // 若二次查询失败，则回退使用轻量行
                            if (!nextStageRow) nextStageRow = nextLight;
                        } else {
                            nextStageRow = nextLight;
                        }
                    }
                } catch (e) { /* ignore */ }

                if (nextStageRow && nextStageRow.Supply_Order_Paystages_SerialNumber) {
                    // 查询下一阶段对应的分期配置以获取 Pay_Time
                    let payTimeNum = 0;
                    try {
                        const suspSerial = String(nextStageRow.Supply_Unit_Price_Staged_Payment_SerialNumber || '').trim();
                        if (suspSerial) {
                            const suspArr = await generalApi.generalQueryByTableNameWithOriginal({ Data: 'supply_unitprice_staged_payment', Condition: `Supply_Unit_Price_Staged_Payment_SerialNumber='${suspSerial.replace(/'/g,"''")}'` });
                            const suspRow = Array.isArray(suspArr) ? suspArr[0] : (suspArr && suspArr.Data && suspArr.Data[0]);
                            payTimeNum = Number((suspRow && suspRow.Pay_Time) || 0);
                        }
                    } catch (e) {}

                // 计算结束时间：开始时间 + 报价阶段 Pay_Time（单位：天）
                const payDays = Number(payTimeNum) || 0;
                let endStr = '';
                if (payDays > 0) {
                    const calc = new Date(Date.now() + payDays * 24 * 3600 * 1000);
                    endStr = getYMDHMSDate(calc);
                }
                    // 提交完整原始行，覆盖时间与操作字段，避免服务端校验失败
                    nextStageRow.Start_Datetime = now;
                    if (endStr) {
                        nextStageRow.End_Datetime = endStr;
                    }
                    nextStageRow.Operation_ID = creator;
                    nextStageRow.Operation_Datetime = now;
                    // 合并下一阶段的时间更新到同一 Modify 数组
                    if (dataset.Modify['supply_order_paystages'] && Array.isArray(dataset.Modify['supply_order_paystages'])) {
                        dataset.Modify['supply_order_paystages'].push(nextStageRow);
                    } else {
                        dataset.Modify['supply_order_paystages'] = [nextStageRow];
                    }
                }

                

                console.log('onConfirmReceipt dataset', dataset);

                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                try { console.log('onConfirmReceipt save result', res); } catch (e) {}
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('已确认收款，下一阶段时间已更新');
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) { this.$message.error('收款确认失败'); }
            finally { this.dialogReceiptVisible = false; this.getList(); }
        },
        getReceipt(Store_SerialNumber,Collection_Amount,Collection_Order_Number,Amount,Collection_Related_Number){
            return[{
                Store_SerialNumber:Store_SerialNumber,
                Order_Type:'2',
                Collection_Date:getYMDHMSDate(),
                Collection_Amount:Collection_Amount,
                Enterprise_Info_SerialNumber:getCookie('enterprise'),
                Children:{
                    collection_detail:[{
                        Collection_Order_Number:Collection_Order_Number,//阶段付款主键
                        Collection_Type:'7',
                        Collection_Related_Number:Collection_Related_Number || '',//收款凭证
                        Amount:Amount, //本次收款
                        Enterprise_Info_SerialNumber:getCookie('enterprise'),
                    }]
                }
            }]
        },
        // 保存发货信息到 supply_order_logistics
        async confirmShip() {
            if (!this.shipContext || !this.shipContext.order) {
                this.$message.error('上下文缺失，无法发货');
                return;
            }
            const order = this.shipContext.order;
            if (!this.shipForm.logisticsCode) {
                this.$message.error('请选择物流公司');
                return;
            }
            if (!this.shipForm.logisticsNumber) {
                this.$message.error('请输入物流单号');
                return;
            }
            this.shipSaving = true;
            try {

                const now = getYMDHMSDate();
                const creator = $.cookie('user') || $.cookie('enterprise') || '';
                const rec = {
                    Supply_Order_Logistics_SerialNumber: '',
                    Supply_Order_SerialNumber: order.Supply_Order_SerialNumber,
                    Logistics_Number: this.shipForm.logisticsNumber,
                    Logistics_Code: this.shipForm.logisticsCode,
                    Delivery_Data: now,
                    Delivery_Quantity: String(this.shipForm.deliveryQuantity || ''),
                    Enterprise_Info_SerialNumber: order.Enterprise_Info_SerialNumber || '',
                    Creater_SerialNumber: creator,
                    Create_Datetime: now,
                    Operation_ID: creator,
                    Operation_Datetime: now,
                };
                // 校验本次发货数量
                if (!this.shipForm.deliveryQuantity) {
                    this.$message.error('请输入本次发货数量');
                    this.shipSaving = false;
                    return;
                }
                const fileName = String(this.shipForm.Picture_URL || '').trim();
                if (fileName) rec.Picture_URL = fileName;
                // 计算累计已发与剩余未发，限制不能超量
                const orderQty = Number(order.Quantity || order.Unit_Quantity || 0);
                let shippedTotal = 0;
                try {
                    const listPrev = await generalApi.generalQueryByTableName({
                        Data: 'supply_order_logistics',
                        Condition: `Supply_Order_SerialNumber='${String(order.Supply_Order_SerialNumber||'').replace(/'/g,"''")}'`
                    });
                    const arrPrev = Array.isArray(listPrev) ? listPrev : (listPrev.Data || []);
                    shippedTotal = (arrPrev || []).reduce((acc, it) => acc + Number(it.Delivery_Quantity || 0), 0);
                } catch (e) { shippedTotal = 0; }
                const inputQty = Number(this.shipForm.deliveryQuantity || 0);
                if (!Number.isFinite(inputQty) || inputQty <= 0) {
                    this.$message.error('本次发货数量需为正数');
                    this.shipSaving = false;
                    return;
                }
                if (Number.isFinite(orderQty) && orderQty > 0 && (inputQty + shippedTotal) > orderQty) {
                    this.$message.error('本次发货超出交易数量');
                    this.shipSaving = false;
                    return;
                }
                const remainAfter = Number.isFinite(orderQty) ? Math.max(orderQty - (inputQty + shippedTotal), 0) : 0;
                

                const dataset = { Add: { supply_order_logistics: [rec] }, Modify: {} };

                // 累加主表发货量并计算未发量：Undelivery_Quantity = Quantity - Delivery_Quantity
                try {
                    const ordArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'supply_order',
                        Condition: `Supply_Order_SerialNumber='${String(order.Supply_Order_SerialNumber||'').replace(/'/g,"''")}'`
                    });
                    const ordRow = Array.isArray(ordArr) ? ordArr[0] : (ordArr && ordArr.Data && ordArr.Data[0]);
                    if (ordRow) {
                        const oldDelivery = Number(ordRow.Delivery_Quantity || 0);
                        const newDelivery = accAdd(oldDelivery, inputQty);
                        const qtyTotal = Number(ordRow.Quantity || ordRow.Unit_Quantity || 0);
                        const unDelivery = Math.max(0, Number((qtyTotal - newDelivery).toFixed(2)));
                        ordRow.Delivery_Quantity = String(newDelivery);
                        ordRow.Undelivery_Quantity = String(unDelivery);
                        ordRow.Operation_ID = creator;
                        ordRow.Operation_Datetime = now;
                        dataset.Modify['supply_order'] = [ordRow];
                    }
                } catch (e) { /* ignore */ }
                try {
                    const stgName = String((this.shipContext && this.shipContext.stage && this.shipContext.stage.stage) || '').trim();
                    const arr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'supply_order_paystages',
                        Condition: `Supply_Order_SerialNumber='${order.Supply_Order_SerialNumber}' AND Stage_Name='${stgName.replace(/'/g,"''")}'`
                    });
                    const ps = Array.isArray(arr) ? arr[0] : (arr.Data && arr.Data[0]);
                    const now2 = getYMDHMSDate();
                    const creator2 = $.cookie('user') || $.cookie('enterprise') || '';
                    if (ps && ps.Supply_Order_Paystages_SerialNumber) {
                        ps.Operation_ID = creator2;
                        ps.Operation_Datetime = now2;
                        // 满额发货置灰发货按钮
                        ps.Ship_Status = (remainAfter <= 0 ? '1' : '0');
                        dataset.Modify['supply_order_paystages'] = [ps];
                    }
                } catch (e) { /* ignore */ }
                // 同步更新“下一阶段”的开始/结束时间（按报价阶段顺序）
                try {
                    const curStageName = String((this.shipContext && this.shipContext.stage && this.shipContext.stage.stage) || '').trim();
                    const sqlArr = await generalApi.generalQueryBySQLSerialNumber({
                        SQLSerialNumber: 'supply_payment_stages',
                        Condition: utf8ToBase64(String(order.Supply_Order_SerialNumber || '')),
                        ExtensionCondition: ''
                    });
                    const rows = Array.isArray(sqlArr) ? sqlArr : [];
                    const curIdx = rows.findIndex(r => String(r.Stage_Name || '').trim() === curStageName);
                    if (curIdx >= 0 && curIdx + 1 < rows.length) {
                        const nextLight = rows[curIdx + 1];
                        let nextStageRow = null;
                        if (nextLight && nextLight.Supply_Order_Paystages_SerialNumber) {
                            const nextArr = await generalApi.generalQueryByTableNameWithOriginal({
                                Data: 'supply_order_paystages',
                                Condition: `Supply_Order_Paystages_SerialNumber='${String(nextLight.Supply_Order_Paystages_SerialNumber).replace(/'/g, "''")}'`
                            });
                            nextStageRow = Array.isArray(nextArr) ? nextArr[0] : (nextArr && nextArr.Data && nextArr.Data[0]);
                        }
                        if (!nextStageRow) nextStageRow = nextLight;

                        // 计算结束时间：开始时间 + Pay_Time（天）
                        let payDays = 0;
                        try {
                            const suspSerial = String(nextStageRow.Supply_Unit_Price_Staged_Payment_SerialNumber || '').trim();
                            if (suspSerial) {
                                const suspArr = await generalApi.generalQueryByTableNameWithOriginal({
                                    Data: 'supply_unitprice_staged_payment',
                                    Condition: `Supply_Unit_Price_Staged_Payment_SerialNumber='${suspSerial.replace(/'/g, "''")}'`
                                });
                                const suspRow = Array.isArray(suspArr) ? suspArr[0] : (suspArr && suspArr.Data && suspArr.Data[0]);
                                payDays = Number((suspRow && suspRow.Pay_Time) || 0);
                            }
                        } catch (e2) { /* ignore */ }
                        let endStr = '';
                        if (payDays > 0) {
                            const calc = new Date(Date.now() + payDays * 24 * 3600 * 1000);
                            endStr = getYMDHMSDate(calc);
                        }

                        nextStageRow.Start_Datetime = now;
                        if (endStr) nextStageRow.End_Datetime = endStr;
                        nextStageRow.Operation_ID = creator;
                        nextStageRow.Operation_Datetime = now;

                        if (!dataset.Modify['supply_order_paystages']) {
                            dataset.Modify['supply_order_paystages'] = [nextStageRow];
                        } else {
                            dataset.Modify['supply_order_paystages'].push(nextStageRow);
                        }
                    }
                } catch (e3) { /* ignore */ }
                // 调试输出：核对通用保存入参结构
                try { console.log('confirmPay dataset', JSON.stringify({ Data: dataset })); } catch (e) {}
                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('发货信息已保存');
                this.dialogShipVisible = false;
                    this.getList();
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) {
                this.$message.error('保存发货信息失败，请稍后再试');
            } finally {
                this.shipSaving = false;
            }
        },

        // 收货：提交收货结构
        async openReceiveDialog(orderRow, stageRow) {
            try {
                const list = await generalApi.generalQueryByTableName({
                    Data: 'supply_order_logistics',
                    Condition: `Supply_Order_SerialNumber='${String(orderRow.Supply_Order_SerialNumber||'').replace(/'/g,"''")}'`
                });
                const arr = Array.isArray(list) ? list : (list.Data || []);

                // 反查物流公司名称（批量查询并映射）
                let nameMap = {};
                try {
                    const codes = [...new Set((arr || []).map(it => it.Logistics_Code).filter(Boolean))];
                    if (codes.length) {
                        const con = `Logistics_Code IN (${codes.map(c => `'${String(c).replace(/'/g,"''")}'`).join(',')})`;
                        const opts = await generalApi.generalQueryByTableName({ Data: 'logistics_info', Condition: con });
                        const oa = Array.isArray(opts) ? opts : (opts.Data || []);
                        (oa || []).forEach(o => { nameMap[o.Logistics_Code] = o.Logistics_Name; });
                    }
                } catch (e) {}

                // 组装列表并兼容图片地址
                const listMap = (arr || []).map(it => {
                    const item = Object.assign({}, it);
                    if (item && item.Logistics_Code) item.Logistics_Name = nameMap[item.Logistics_Code] || item.Logistics_Name || '';
                    if (item && item.Picture_URL && !(String(item.Picture_URL).startsWith('http'))) {
                        item.Picture_URL = (typeof imageApi !== 'undefined' ? imageApi : '') + item.Picture_URL;
                    }
                    return item;
                });
                this.receiveLogisticsList = listMap;

                // 选择最新的一条用于图片展示
                let rec = arr && arr[0];
                if (arr && arr.length > 1) {
                    rec = arr.slice().sort((a,b)=> new Date(b.Create_Datetime||0) - new Date(a.Create_Datetime||0))[0];
                }
                if (rec && rec.Logistics_Code) rec.Logistics_Name = nameMap[rec.Logistics_Code] || rec.Logistics_Name;
                if (rec && rec.Picture_URL && !(String(rec.Picture_URL).startsWith('http'))) {
                    rec.Picture_URL = (typeof imageApi !== 'undefined' ? imageApi : '') + rec.Picture_URL;
                }

                this.receiveView = rec || null;
                this.receiveContext = { order: orderRow, stage: stageRow };
                this.receiveForm = { receiptQuantity: '' };

                // 单位文案
                try {
                    const serial = (orderRow && orderRow.Article_Unit_SerialNumber)
                        || (orderRow && orderRow.originSupply && orderRow.originSupply.Article_Unit_SerialNumber)
                        || (this.pageSupply && this.pageSupply.Article_Unit_SerialNumber)
                        || '';
                    const txt = this.getUnitText(serial);
                    this.receiveUnitText = (txt && String(txt).trim()) || '单位';
                } catch (e) { this.receiveUnitText = '单位'; }

                this.dialogReceiveVisible = true;
            } catch (e) {
                this.$message.error('查询物流信息失败');
            }
        },
        // 收货确认：保存入库数量到 purchase_receipt/purchase_receipt_detail
        async confirmReceive() {
            try {
                if (!this.receiveContext || !this.receiveContext.order) { this.dialogReceiveVisible=false; return; }
                const order = this.receiveContext.order;
                const stage = (this.receiveContext && this.receiveContext.stage) || {};
                const inputQtyStr = String(this.receiveForm && this.receiveForm.receiptQuantity || '').trim();
                const inputQty = Number(inputQtyStr);
                if (!inputQtyStr || !(Number.isFinite(inputQty)) || inputQty <= 0) {
                    this.$message.error('请输入有效的入库数量');
                    return;
                }
                const condSafeOrder = String(order.Supply_Order_SerialNumber || '').replace(/'/g, "''");
                // 交易数量取 supply_order.Quantity
                const receiptQuantitysStr = String(order.Quantity || order.Unit_Quantity || '').trim();
                // 商品流水号取自 originSupply.Article_SerialNumber
                const articleSerial = (order && order.originSupply && order.originSupply.Article_SerialNumber)
                    || (this.pageSupply && this.pageSupply.Article_SerialNumber) || '';
                const purchaseOrderSerial = String(order.Supply_Order_SerialNumber || '').trim();

                // 取最新物流记录的凭证图片，作为收货凭证写入明细
                let receiptVoucher = '';
                try {
                    const pic = (this.receiveView && this.receiveView.Picture_URL) || '';
                    if (pic) {
                        // 仅保存相对路径：去掉前端拼接的 imageApi 前缀
                        const api = (typeof imageApi !== 'undefined' ? imageApi : '');
                        receiptVoucher = (api && String(pic).startsWith(api)) ? String(pic).slice(api.length) : String(pic);
                    }
                } catch (e) { receiptVoucher = ''; }
                const dataset = { Add: { purchase_receipt: this.getConfirmReceive(receiptQuantitysStr, purchaseOrderSerial, articleSerial, inputQtyStr, receiptVoucher), base_operation_log: [] }, Modify: {} };

                // 累加主表收货量并计算未收量：Unreceipt_Quantity = Quantity - Receipt_Quantity
                try {
                    const ordArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'supply_order',
                        Condition: `Supply_Order_SerialNumber='${condSafeOrder}'`
                    });
                    const ordRow = Array.isArray(ordArr) ? ordArr[0] : (ordArr && ordArr.Data && ordArr.Data[0]);
                    if (ordRow) {
                        const oldReceipt = Number(ordRow.Receipt_Quantity || 0);
                        const newReceipt = accAdd(oldReceipt, inputQty);
                        const qtyTotal = Number(ordRow.Quantity || ordRow.Unit_Quantity || 0);
                        const unReceipt = Math.max(0, Number((qtyTotal - newReceipt).toFixed(2)));
                        ordRow.Receipt_Quantity = String(newReceipt);
                        ordRow.Unreceipt_Quantity = String(unReceipt);
                        const nowRec2 = getYMDHMSDate();
                        const creatorRec2 = $.cookie('user') || $.cookie('enterprise') || '';
                        ordRow.Operation_ID = creatorRec2;
                        ordRow.Operation_Datetime = nowRec2;
                        dataset.Modify['supply_order'] = [ordRow];
                    }
                } catch (e) { /* ignore */ }

                // 聚合已收货数量，判断是否收满交易数，置灰到货阶段按钮
                try {
                    const pr = await generalApi.generalQueryByTableName({ Data: 'purchase_receipt_detail', Condition: `Purchase_Order_SerialNumber='${condSafeOrder}'` });
                    const prArr = Array.isArray(pr) ? pr : (pr.Data || []);
                    const already = (prArr || []).reduce((acc, it) => acc + Number(it.Receipt_Quantity || 0), 0);
                    const tradingQty = Number(receiptQuantitysStr || 0);
                    const newTotal = already + inputQty;
                    const shouldGray = Number.isFinite(tradingQty) && tradingQty > 0 && newTotal >= tradingQty;
                    const stageModify = {};
                    if (stage) {
                        let fullStageRow = null;
                        const stgName = String(stage.stage || '').trim();
                        // 优先按阶段流水号获取“完整原始行”，失败则回退按订单+阶段名
                        if (stage.serial) {
                            try {
                                const curArr = await generalApi.generalQueryByTableNameWithOriginal({
                                    Data: 'supply_order_paystages',
                                    Condition: `Supply_Order_Paystages_SerialNumber='${String(stage.serial).replace(/'/g, "''")}'`
                                });
                                fullStageRow = Array.isArray(curArr) ? curArr[0] : (curArr && curArr.Data && curArr.Data[0]);
                            } catch (e2) { /* ignore */ }
                        }
                        if (!fullStageRow) {
                            try {
                                const fbArr = await generalApi.generalQueryByTableNameWithOriginal({
                                    Data: 'supply_order_paystages',
                                    Condition: `Supply_Order_SerialNumber='${condSafeOrder}' AND Stage_Name='${stgName.replace(/'/g,"''")}'`
                                });
                                fullStageRow = Array.isArray(fbArr) ? fbArr[0] : (fbArr && fbArr.Data && fbArr.Data[0]);
                            } catch (e3) { /* ignore */ }
                        }
                        if (fullStageRow) {
                            fullStageRow.Receipt_Ship_Status = shouldGray ? '1' : '0';
                            // 记录操作人及时间，保持与其他更新一致
                            const nowRec = getYMDHMSDate();
                            const creatorRec = $.cookie('user') || $.cookie('enterprise') || '';
                            fullStageRow.Operation_ID = creatorRec;
                            fullStageRow.Operation_Datetime = nowRec;
                            if (!dataset.Modify['supply_order_paystages']) dataset.Modify['supply_order_paystages'] = [];
                            dataset.Modify['supply_order_paystages'].push(fullStageRow);
                        }
                    }
                } catch (e) { /* 查询失败不阻塞保存 */ }
                this.receiveSaving = true;
                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('已确认收货并保存入库记录');
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                    return;
                }
            } catch (e) { this.$message.error('收货保存失败'); }
            finally { this.receiveSaving = false; this.dialogReceiveVisible = false; this.getList(); }
        },
        getConfirmReceive(Receipt_Quantitys,Purchase_Order_SerialNumber,Article_SerialNumber,Receipt_Quantity,Receipt_Related_Number){
            return[{
                Receipt_Date:getYMDHMSDate(),
                Receipt_Type:'0',//仓库
                Receipt_Quantitys:Receipt_Quantitys,//交易数量
                Enterprise_Info_SerialNumber:getCookie('enterprise'),
                Children:{
                    purchase_receipt_detail:[{
                        Purchase_Order_SerialNumber:Purchase_Order_SerialNumber,//交易单号
                        Article_SerialNumber:Article_SerialNumber,//商品流水号
                        Receipt_Quantity:Receipt_Quantity,//入库数量
                        Receipt_Related_Number:Receipt_Related_Number || '',//收货凭证
                        Enterprise_Info_SerialNumber:getCookie('enterprise'),
                    }]
                }
            }]
        },
        async confirmPay() {
            if (!this.payContext || !this.payContext.order) {
                this.$message.error('上下文缺失，无法付款');
                return;
            }
            const order = this.payContext.order;
            const stage = this.payContext.stage || {};
            const amountNum = Number(this.payForm.amount || 0);
            if (!Number.isFinite(amountNum) || amountNum <= 0) {
                this.$message.error('请输入有效的付款金额');
                return;
            }
            this.paySaving = true;
            try {
                
                // 1) 查询订单原值以便累计 Paid_Amount
                const orderArr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'supply_order',
                    Condition: `Supply_Order_SerialNumber='${order.Supply_Order_SerialNumber}'`
                });
                const od = orderArr[0];
                const oldPaid = Number(od.Paid_Amount || 0);
                const newPaid = accAdd(oldPaid, amountNum);
                od.Paid_Amount = String(newPaid);
                // 同步剩余应付金额 = 订单总价 - 已付金额
                const orderTotalAmountNum = Number(order.Amount || 0);
                const newRemainNum = Number((orderTotalAmountNum - newPaid).toFixed(2));
                od.Remain_Amount = String(newRemainNum >= 0 ? newRemainNum : 0);

                // 2) 查询当前阶段付款记录：累计
                let stageModify = null;
                let stageAdd = null;
                // 计算本次应付金额 Trading_Amount = supply_order.Amount * Percent%
                const totalAmount = Number(order.Amount || 0);
                const hasPercent = !(stage.percent === undefined || stage.percent === null || stage.percent === '');
                const percentVal = hasPercent ? Number(stage.percent) : NaN;
                const tradingAmountNum = (Number.isFinite(totalAmount) && hasPercent && Number.isFinite(percentVal))
                    ? Number((totalAmount * percentVal / 100).toFixed(2))
                    : Number((stage.dueAmount !== undefined && stage.dueAmount !== null && stage.dueAmount !== '' ? stage.dueAmount : 0));
                try {
                    const condStr = stage.serial
                        ? `Supply_Order_Paystages_SerialNumber='${String(stage.serial).replace(/'/g, "''")}'`
                        : `Supply_Order_SerialNumber='${order.Supply_Order_SerialNumber}' AND Stage_Name='${String(stage.stage || '').replace(/'/g, "''")}'`;
                    const stageArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'supply_order_paystages',
                        Condition: condStr
                    });
                    if (!Array.isArray(stageArr) || stageArr.length < 1) {
                        this.$message.error('付款阶段不存在，无法操作');
                        this.paySaving = false;
                        return;
                    }
                    // 只修改查到的唯一阶段记录
                    stageModify = stageArr[0];
                    const sOld = Number(stageModify.Paid_Amount || 0);
                    // 阶段目标应付金额（优先取已有 Trading_Amount，否则用计算值）
                    const targetTrading = Number(stageModify.Trading_Amount || tradingAmountNum || 0);
                    // 不允许超付：本次累计不得超过目标应付
                    if (Number.isFinite(targetTrading) && targetTrading > 0 && accAdd(sOld, amountNum) > targetTrading) {
                        this.$message.error('付款金额超出本阶段应付');
                        this.paySaving = false;
                        return;
                    }
                    const newStagePaid = accAdd(sOld, amountNum);
                    stageModify.Paid_Amount = String(newStagePaid);
                    // 同步阶段剩余未付：Remain_Amount = Trading_Amount - Paid_Amount
                    if (Number.isFinite(targetTrading)) {
                        const remainStage = Math.max(Number((targetTrading - newStagePaid).toFixed(2)), 0);
                        stageModify.Remain_Amount = String(remainStage);
                    }
                    // 统一企业编号
                    if (!stageModify.Enterprise_Info_SerialNumber) {
                        stageModify.Enterprise_Info_SerialNumber = getCookie('enterprise');
                    }
                    // 同步本次应付金额 Trading_Amount
                    if (Number.isFinite(tradingAmountNum)) stageModify.Trading_Amount = String(tradingAmountNum);
                    const nowStr = getYMDHMSDate();
                    stageModify.Collection_Date = nowStr;
                    stageModify.Paid_Datetime = nowStr;
                    // 状态：累计达到目标视为“已付款”，否则仍“待付款”
                    if (Number.isFinite(targetTrading) && targetTrading > 0 && newStagePaid >= targetTrading) {
                        stageModify.Pay_Status = '1'; // 满额置灰
                    } else {
                        stageModify.Pay_Status = '0';
                    }
                } catch (e) {
                    
                }

                const supplierSerial = (order && order.originSupply && order.originSupply.Enterprise_Info_SerialNumber)
                    ? order.originSupply.Enterprise_Info_SerialNumber
                    : (this.enterpriseId || '');
                const dataset = { Modify: { supply_order: [od], supply_order_paystages: [stageModify] }, Add: { payment: this.getPayment(amountNum, stage.serial, (this.payForm && this.payForm.Picture_URL) ? this.payForm.Picture_URL : '', supplierSerial, tradingAmountNum) } };
                console.log(dataset);//付款
                const res = await generalApi.generalSaveByRequestBody({ Data: dataset });
                if (res && (res.Status === 'success' || (Array.isArray(res) && res.every(r => r.Status === 'success')))) {
                    this.$message.success('付款成功');
                    this.dialogPayVisible = false;
                    this.getList();
                } else {
                    const msg = (res && (res.Message || res.Error || res.msg)) || '保存失败';
                    this.$message.error(msg);
                }
            } catch (e) {
                this.$message.error('付款失败，请稍后再试');
            } finally {
                this.paySaving = false;
            }
        },
        getPayment(Amount, Business_Order_SerialNumber,Payment_Voucher_Picture, Supplier_SerialNumber, StageAmount) {
            return [{
                Supplier_SerialNumber: Supplier_SerialNumber || '',
                Payment_Date:getYMDHMSDate(),
                Payment_Amount:String(Amount),
                Amount:String(StageAmount),
                Bank_Voucher_SerialNumber:'',
                Enterprise_Info_SerialNumber:getCookie('enterprise'),
                Children: {
                    payment_detail:[{
                        Business_Order_SerialNumber:Business_Order_SerialNumber,
                        Payment_Method:'电子汇款',
                        Payment_Type:'0',
                        Amount:String(Amount),
                        Enterprise_Info_SerialNumber:getCookie('enterprise'),
                    }],
                    payment_voucher:[{
                        Payment_Voucher_Picture:Payment_Voucher_Picture,
                        Enterprise_Info_SerialNumber:getCookie('enterprise'),
                    }]
                }
            }]
        },
        
        // 4-待付款，5-已付款，6-待发货，7-已发货
        formatPayStageStatus(st) {
            const s = String(st || '').trim();
            if (s === '4' || s === '待付款') return '待付款';
            if (s === '5' || s === '已付款') return '已付款';
            if (s === '6' || s === '待发货') return '待发货';
            if (s === '7' || s === '已发货') return '已发货';
            return '待付款';
        },
        handlePageChange(page) {
            this.form.PageNumber = page;
            this.getList();
        },
        getList() {
            const enterpriseId = $.cookie('enterprise') || '';
            const keyword = this.form.value || '';
            const supplyId = (function () {
                try { return getQueryObject(window.location.href, 'supplyId') || ''; } catch (e) { return ''; }
            })();
            const applyId = (function () {
                try { return getQueryObject(window.location.href, 'applyId') || ''; } catch (e) { return ''; }
            })();
            const orderSerial = (function () {
                try { return getQueryObject(window.location.href, 'orderSerial') || ''; } catch (e) { return ''; }
            })();
            // 记录当前 SupplyId 以便顶部展示原信息
            this.currentSupplyId = supplyId;
            // 记录当前企业与来源标记（从“我的采购”进入时隐藏操作按钮）
            this.enterpriseId = enterpriseId;
            this.fromApplyDetail = !!applyId;
            this.currentOrderSerial = orderSerial;

            // 支持：按当前企业或指定报价编号过滤（状态：0待接受、2已接受、3已拒绝）
            let condition = '';
            if (orderSerial) {
                // 优先按交易单号精确查询该订单
                const safeSerial = String(orderSerial).replace(/'/g, "''");
                condition = `Supply_Order_SerialNumber='${safeSerial}'`;
            } else {
                condition = `Row_Status IN ('0','2','3')`;
                if (applyId) {
                    // 精确按照申请流水号筛选
                    condition += ` AND Supply_Order_SerialNumber='${applyId}'`;
                } else if (supplyId) {
                    // 按报价编号筛选
                    condition += ` AND Supply_Unit_Price_SerialNumber='${supplyId}'`;
                } else {
                    // 默认：当前企业名下的有效报价单关联的订单
                    condition += ` AND Supply_Unit_Price_SerialNumber IN (
                        SELECT Supply_Unit_Price_SerialNumber FROM supply_unitprice
                        WHERE Row_Status='0' AND Enterprise_Info_SerialNumber='${enterpriseId}'
                    )`;
                }
                if (keyword) {
                    const kw = String(keyword).replace(/'/g, "''");
                    condition += ` AND (Supply_Order_SerialNumber LIKE '%${kw}%' OR Enterprise_Info_SerialNumber LIKE '%${kw}%')`;
                }
            }

            httpRequest({
                url: '/generalBusiness/generalQueryByTableName',
                data: {
                    Data: 'supply_order',
                    Condition: condition,
                    PageNumber: this.form.PageNumber,
                    RowAmount: this.form.RowAmount,
                },
                type: 'GET'
            }).then(async res => {
                // res 可能是数组或分页对象，兼容处理
                // 统一拿到数组结果
                const arr = Array.isArray(res) ? res : (res.Data || []);
                // 仅保留当前订单（列表第一条）
                this.list = (Array.isArray(arr) && arr.length > 0) ? [arr[0]] : [];
                this.total = this.list.length;
                // 批量查询供应单原信息（supply_unitprice），并挂载到订单上方展示
                const supplyIds = [...new Set((this.list || []).map(i => i.Supply_Unit_Price_SerialNumber).filter(Boolean))];
                if (supplyIds.length > 0) {
                    try {
                        const supRes = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: {
                                Data: 'supply_unitprice',
                                Condition: `Supply_Unit_Price_SerialNumber IN (${supplyIds.map(id => `'${id}'`).join(',')})`
                            },
                            type: 'GET'
                        });
                        const supArr = Array.isArray(supRes) ? supRes : (supRes.Data || []);
                        const supMap = {};
                        supArr.forEach(s => { supMap[s.Supply_Unit_Price_SerialNumber] = s; });
                        this.list = this.list.map(row => ({
                            ...row,
                            originSupply: supMap[row.Supply_Unit_Price_SerialNumber] || null
                        }));
                        const firstSupplyId = (this.list[0] && this.list[0].Supply_Unit_Price_SerialNumber) || '';
                        this.pageSupply = supMap[this.currentSupplyId] || supMap[firstSupplyId] || null;
                        // 记录当前订单
                        this.currentOrder = this.list[0] || null;

                        // 批量查询单位中文名（article_unit.Unit），构建映射 unitMap
                        const unitSerials = [...new Set((supArr || []).map(s => s.Article_Unit_SerialNumber).filter(Boolean))];
                        if (unitSerials.length > 0) {
                            try {
                                const unitRes = await httpRequest({
                                    url: '/generalBusiness/generalQueryByTableName',
                                    data: {
                                        Data: 'article_unit',
                                        Condition: `Article_Unit_SerialNumber IN (${unitSerials.map(u => `'${u}'`).join(',')})`
                                    },
                                    type: 'GET'
                                });
                                const unitArr = Array.isArray(unitRes) ? unitRes : (unitRes.Data || []);
                                const map = {};
                                (unitArr || []).forEach(u => { if (u.Article_Unit_SerialNumber) map[u.Article_Unit_SerialNumber] = u.Unit; });
                                this.unitMap = map;
                            } catch (e) { /* 单位加载失败不阻塞 */ }
                        }

                        // 查询报价阶段方案（supply_unitprice_staged_payment），用于在 SQL 返回未携带 Percent 时按阶段主键补齐 Percent
                        let stagedPlanBySerial = {};
                        try {
                            const spRes = await httpRequest({
                                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                                data: {
                                    Data: 'supply_unitprice_staged_payment',
                                    Condition: `Supply_Unit_Price_SerialNumber IN (${supplyIds.map(id => `'${id}'`).join(',')})`
                                },
                                type: 'POST'
                            });
                            const spArr = Array.isArray(spRes) ? spRes : (spRes.Data || []);
                            (spArr || []).forEach(sp => {
                                const k = sp.Supply_Unit_Price_Staged_Payment_SerialNumber;
                                if (k) stagedPlanBySerial[k] = sp;
                            });
                        } catch (e) { /* ignore staged plan failure */ }

                       
                        // 通过 SQL 标识 supply_payment_stages（返回带 Row_Status、Paid_Amount 等），再映射到固定四阶段
                        try {
                            const sqlResults = await Promise.all((this.list || []).map(row =>
                                generalApi.generalQueryBySQLSerialNumber({
                                    SQLSerialNumber: 'supply_payment_stages',
                                    Condition: utf8ToBase64(String(row.Supply_Order_SerialNumber || '')),
                                    ExtensionCondition: ''
                                }).catch(() => [])
                            ));
                            const stageOrder = ['定金','发货','到货','尾款'];
                            this.list = (this.list || []).map((row, idx) => {
                                const arr = sqlResults[idx];
                                const rows = Array.isArray(arr) ? arr : [];

                                const stages = rows.map(rec => {
                                    // 付款比例仅显示 Percent 字段；若 SQL 未带 Percent，则按报价侧阶段主键回填 Percent
                                    let pctRaw = (rec.Percent !== undefined && rec.Percent !== null && rec.Percent !== '') ? rec.Percent : '';
                                    if (!pctRaw && rec.Supply_Unit_Price_Staged_Payment_SerialNumber) {
                                        const sp = stagedPlanBySerial[rec.Supply_Unit_Price_Staged_Payment_SerialNumber];
                                        if (sp && sp.Percent !== undefined && sp.Percent !== null && sp.Percent !== '') {
                                            pctRaw = sp.Percent;
                                        }
                                    }
                                    const pctNum = (pctRaw !== '' ? Number(pctRaw) : NaN);
                                    const dueRaw = (rec.Due_Amount !== undefined && rec.Due_Amount !== null && rec.Due_Amount !== '')
                                        ? Number(rec.Due_Amount) : (rec.Trading_Amount !== undefined ? Number(rec.Trading_Amount) : '');
                                    const begin = rec.Start_Datetime ? getYMDDate(rec.Start_Datetime) : '';
                                    const end = rec.End_Datetime ? getYMDDate(rec.End_Datetime) : '';
                                    // 阶段款项：已付款/未付款、应收款=应付款、已收款/未收款
                                    const paidNum = Number(rec.Paid_Amount || 0);
                                    const remainRaw = (rec.Remain_Amount !== undefined && rec.Remain_Amount !== null && rec.Remain_Amount !== '')
                                        ? Number(rec.Remain_Amount) : (Number.isFinite(dueRaw) ? Number((dueRaw - paidNum).toFixed(2)) : 0);
                                    const collectedNum = Number(rec.Collection_Amount || 0);
                                    const uncollectedRaw = (rec.Unamount !== undefined && rec.Unamount !== null && rec.Unamount !== '')
                                        ? Number(rec.Unamount) : (Number.isFinite(dueRaw) ? Number((dueRaw - collectedNum).toFixed(2)) : 0);
                                    return {
                                        stage: rec.Stage_Name || '',
                                        percent: Number.isFinite(pctNum) ? pctNum : '',
                                        dueAmount: Number.isFinite(dueRaw) ? Number(dueRaw.toFixed(2)) : '',
                                        receivableAmount: Number.isFinite(dueRaw) ? Number(dueRaw.toFixed(2)) : '',
                                        payWindow: (begin && end) ? `${begin} — ${end}` : '',
                                        status: this.formatPayStageStatus(rec.Row_Status),
                                        serial: rec.Supply_Order_Paystages_SerialNumber || '',
                                        quoteStageSerial: rec.Supply_Unit_Price_Staged_Payment_SerialNumber || '',
                                        paidAmount: Number(paidNum || 0),
                                        unpaidAmount: Number.isFinite(remainRaw) ? remainRaw : 0,
                                        collectedAmount: Number(collectedNum || 0),
                                        uncollectedAmount: Number.isFinite(uncollectedRaw) ? uncollectedRaw : 0,
                                        Pay_Status: rec.Pay_Status,
                                        Receipt_Pay_Status: rec.Receipt_Pay_Status,
                                        Ship_Status: rec.Ship_Status,
                                        Receipt_Ship_Status: rec.Receipt_Ship_Status,
                                        // Invoic_Status: rec.Invoic_Status,
                                        // Receipt_Invoic_Status: rec.Receipt_Invoic_Status
                                    };
                                });
                                const stageDict = {};
                                stages.forEach(s => { stageDict[String(s.stage||'').trim()] = s; });
                                const fixed = stageOrder.map(name => {
                                    const s = stageDict[name] || {};
                                    return {
                                        stage: name,
                                        percent: (s.percent !== undefined && s.percent !== null && s.percent !== '') ? s.percent : '',
                                        dueAmount: (s.dueAmount !== undefined && s.dueAmount !== null && s.dueAmount !== '') ? s.dueAmount : '',
                                        receivableAmount: (s.receivableAmount !== undefined && s.receivableAmount !== null && s.receivableAmount !== '') ? s.receivableAmount : ((s.dueAmount !== undefined && s.dueAmount !== null && s.dueAmount !== '') ? s.dueAmount : ''),
                                        payWindow: (s.payWindow !== undefined && s.payWindow !== null && s.payWindow !== '') ? s.payWindow : '',
                                        status: s.status || '待付款',
                                        serial: s.serial || '',
                                        quoteStageSerial: s.quoteStageSerial || '',
                                        paidAmount: (s.paidAmount !== undefined) ? s.paidAmount : 0,
                                        unpaidAmount: (s.unpaidAmount !== undefined) ? s.unpaidAmount : 0,
                                        collectedAmount: (s.collectedAmount !== undefined) ? s.collectedAmount : 0,
                                        uncollectedAmount: (s.uncollectedAmount !== undefined) ? s.uncollectedAmount : 0,
                                        // 绑定按钮置灰状态（0 常亮，1 置灰）
                                        Pay_Status: (s.Pay_Status !== undefined && s.Pay_Status !== null && s.Pay_Status !== '') ? String(s.Pay_Status) : '0',
                                        Receipt_Pay_Status: (s.Receipt_Pay_Status !== undefined && s.Receipt_Pay_Status !== null && s.Receipt_Pay_Status !== '') ? String(s.Receipt_Pay_Status) : '0',
                                        Ship_Status: (s.Ship_Status !== undefined && s.Ship_Status !== null && s.Ship_Status !== '') ? String(s.Ship_Status) : '0',
                                        Receipt_Ship_Status: (s.Receipt_Ship_Status !== undefined && s.Receipt_Ship_Status !== null && s.Receipt_Ship_Status !== '') ? String(s.Receipt_Ship_Status) : '0',
                                        // Invoic_Status: (s.Invoic_Status !== undefined && s.Invoic_Status !== null && s.Invoic_Status !== '') ? String(s.Invoic_Status) : '0',
                                        // Receipt_Invoic_Status: (s.Receipt_Invoic_Status !== undefined && s.Receipt_Invoic_Status !== null && s.Receipt_Invoic_Status !== '') ? String(s.Receipt_Invoic_Status) : '0'
                                    };
                                });
                                return { ...row, _stagePaymentsDisplay: stages, _stagePaymentsFixed: fixed };
                            });
                        } catch (e) {
                            // 查询失败忽略
                        }
                    } catch (e) {
                        
                    }
                }
            }).catch(() => {
                this.$message.error('查询失败，请稍后再试');
            });
        },
        // 阶段状态控制按钮可操作性：根据新字段控制
        actionEnabled(stageRow, action) {
            const payDisabled = String((stageRow && (stageRow.Pay_Status !== undefined ? stageRow.Pay_Status : stageRow.payStatus)) || '') === '1';
            const receiptDisabled = String((stageRow && (stageRow.Receipt_Pay_Status !== undefined ? stageRow.Receipt_Pay_Status : stageRow.receiptPayStatus)) || '') === '1';
            const shipDisabled = String((stageRow && (stageRow.Ship_Status !== undefined ? stageRow.Ship_Status : stageRow.shipStatus)) || '') === '1';
            const receiveDisabled = String((stageRow && (stageRow.Receipt_Ship_Status !== undefined ? stageRow.Receipt_Ship_Status : stageRow.receiveShipStatus)) || '') === '1';
            // const invoicDisabled = String((stageRow && (stageRow.Invoic_Status !== undefined ? stageRow.Invoic_Status : stageRow.invoicStatus)) || '') === '1';
            // const receiptInvoicDisabled = String((stageRow && (stageRow.Receipt_Invoic_Status !== undefined ? stageRow.Receipt_Invoic_Status : stageRow.receiptInvoicStatus)) || '') === '1';
            switch (action) {
                case 'pay': return !payDisabled;
                case 'receipt': return !receiptDisabled;
                case 'ship': return !shipDisabled;
                case 'receive': return !receiveDisabled;
                // case 'invoic': return !invoicDisabled;
                // case 'receipt_invoic': return !receiptInvoicDisabled;
                default:
                    return true;
            }
        },
        // 操作按钮可见性：仅发布供应的企业可见；从“我的采购”进入（applyId）则不可见
        canOperate(row) {
            if (this.fromApplyDetail) return false;
            const pubEnt = (row && row.originSupply && row.originSupply.Enterprise_Info_SerialNumber) || '';
            return pubEnt && this.enterpriseId && String(pubEnt) === String(this.enterpriseId);
        },
        // 合同确认状态格式化与判定
        formatContractStatus(st) {
            const s = String(st || '');
            if (s === '00') return '未确认';
            if (s === '01') return '卖方已确认';
            if (s === '10') return '买方已确认';
            if (s === '11') return '买卖双方确认';
            return '未确认';
        },
        contractStatusTagType(st) {
            const s = String(st || '');
            if (s === '11') return 'success';
            if (s === '01' || s === '10') return 'warning';
            return 'info';
        },
        isContractConfirmed(row) {
            return String((row && row.Contract_Status) || '') === '11';
        },
        // 卖方确认：若买方已确认(10)则置为11，否则置为01
        async confirmByB(row) {
            if (!row || !row.Supply_Order_SerialNumber) return;
            try {
                const now = getYMDHMSDate();
                const creator = getCookie('user') || '';
                const current = String(row.Contract_Status || '00');
                const nextStatus = current === '10' ? '11' : '01';
                // 查询原订单记录，完整更新
                const orderArr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'supply_order',
                    Condition: `Supply_Order_SerialNumber='${String(row.Supply_Order_SerialNumber||'').replace(/'/g, "''")}'`
                });
                if (!Array.isArray(orderArr) || orderArr.length !== 1) throw new Error('未找到订单数据或存在重复记录');
                const od = { ...orderArr[0], Contract_Status: nextStatus, Operation_ID: creator, Operation_Datetime: now };
                const dataset = { Add: {}, Modify: { supply_order: [od] } };
                const res = await httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: dataset }) });
                if (!(res && res.Status === 'success')) { throw new Error(res?.Message || '保存失败'); }
                row.Contract_Status = nextStatus;
                // 双方都确认：按两个主键查原值，更新“定金”阶段开始时间（supply_order_paystages）
                if (nextStatus === '11') {
                    const unitPriceIdB = orderArr[0].Supply_Unit_Price_SerialNumber || '';
                    const orderSerialB = row.Supply_Order_SerialNumber || '';
                    if (unitPriceIdB && orderSerialB) {
                        try {
                            const planArrB = await generalApi.generalQueryByTableName({
                                Data: 'supply_unitprice_staged_payment',
                                Condition: `Supply_Unit_Price_SerialNumber='${String(unitPriceIdB).replace(/'/g, "''")}' AND Stage_Name='${String('定金').replace(/'/g, "''")}'`
                            });
                            const planB = Array.isArray(planArrB) ? planArrB[0] : null;
                            const stagedSerialB = planB ? planB.Supply_Unit_Price_Staged_Payment_SerialNumber : '';
                            if (stagedSerialB) {
                                const paystagesB = await generalApi.generalQueryByTableNameWithOriginal({
                                    Data: 'supply_order_paystages',
                                    Condition: `Supply_Order_SerialNumber='${String(orderSerialB).replace(/'/g, "''")}' AND Supply_Unit_Price_Staged_Payment_SerialNumber='${String(stagedSerialB).replace(/'/g, "''")}'`
                                });
                                if (Array.isArray(paystagesB) && paystagesB.length === 1) {
                                    // 计算结束时间：开始时间 + 报价阶段 Pay_Time（单位：天）
                                    const payDaysB = Number(planB && planB.Pay_Time) || 0;
                                    let endStrB = '';
                                    if (payDaysB > 0) {
                                        const calcB = new Date(Date.now() + payDaysB * 24 * 3600 * 1000);
                                        endStrB = getYMDHMSDate(calcB);
                                    }
                                    // 修改开始时间与结束时间（覆盖写入）
                                    paystagesB[0].Start_Datetime = now;
                                    if (endStrB) {
                                        paystagesB[0].End_Datetime = endStrB;
                                    }
                                    paystagesB[0].Operation_ID = creator;
                                    paystagesB[0].Operation_Datetime = now;
                                    await generalApi.generalSaveByRequestBody({
                                        Data: { Modify: { supply_order_paystages: paystagesB } }
                                    });
                                }
                            }
                        } catch (e) { /* ignore */ }
                    }
                    this.getList();
                }
                this.$message.success(nextStatus === '11' ? '卖方确认完成，合同已双边确认' : '卖方已确认合同');
            } catch (e) {
                console.error(e);
                this.$message.error('卖方确认失败，请稍后重试');
            }
        },
        // 买方确认：若卖方已确认(01)则置为11，否则置为10
        async confirmByA(row) {
            if (!row || !row.Supply_Order_SerialNumber) return;
            try {
                const now = getYMDHMSDate();
                const creator = getCookie('user') || '';
                const current = String(row.Contract_Status || '00');
                const nextStatus = current === '01' ? '11' : '10';
                // 查询原订单记录，完整更新
                const orderArr = await generalApi.generalQueryByTableNameWithOriginal({
                    Data: 'supply_order',
                    Condition: `Supply_Order_SerialNumber='${String(row.Supply_Order_SerialNumber||'').replace(/'/g, "''")}'`
                });
                if (!Array.isArray(orderArr) || orderArr.length !== 1) throw new Error('未找到订单数据或存在重复记录');
                const od = { ...orderArr[0], Contract_Status: nextStatus, Operation_ID: creator, Operation_Datetime: now };
                const dataset = { Add: {}, Modify: { supply_order: [od] } };
                const res = await httpRequest({ contentType: 'JSON', url: '/generalBusiness/generalSaveByRequestBody', data: JSON.stringify({ Data: dataset }) });
                if (!(res && res.Status === 'success')) { throw new Error(res?.Message || '保存失败'); }
                row.Contract_Status = nextStatus;
                // 双方都确认：按两个主键查原值，更新“定金”阶段开始时间（supply_order_paystages）
                if (nextStatus === '11') {
                    const unitPriceIdA = orderArr[0].Supply_Unit_Price_SerialNumber || '';
                    const orderSerialA = row.Supply_Order_SerialNumber || '';
                    if (unitPriceIdA && orderSerialA) {
                        try {
                            // 取“定金”阶段的报价主键（SUSP…）
                            const planArrA = await generalApi.generalQueryByTableName({
                                Data: 'supply_unitprice_staged_payment',
                                Condition: `Supply_Unit_Price_SerialNumber='${String(unitPriceIdA).replace(/'/g, "''")}' AND Stage_Name='${String('定金').replace(/'/g, "''")}'`
                            });
                            const planA = Array.isArray(planArrA) ? planArrA[0] : null;
                            const stagedSerialA = planA ? planA.Supply_Unit_Price_Staged_Payment_SerialNumber : '';
                            if (stagedSerialA) {
                                // 用原值接口按两个主键查唯一阶段记录
                                const paystagesA = await generalApi.generalQueryByTableNameWithOriginal({
                                    Data: 'supply_order_paystages',
                                    Condition: `Supply_Order_SerialNumber='${String(orderSerialA).replace(/'/g, "''")}' AND Supply_Unit_Price_Staged_Payment_SerialNumber='${String(stagedSerialA).replace(/'/g, "''")}'`
                                });
                                if (Array.isArray(paystagesA) && paystagesA.length === 1) {
                                    // 计算结束时间：开始时间 + 报价阶段 Pay_Time（单位：天）
                                    const payDays = Number(planA && planA.Pay_Time) || 0;
                                    let endStr = '';
                                    if (payDays > 0) {
                                        const calc = new Date(Date.now() + payDays * 24 * 3600 * 1000);
                                        endStr = getYMDHMSDate(calc);
                                    }
                                    // 修改开始时间与结束时间（覆盖写入）
                                    paystagesA[0].Start_Datetime = now;
                                    if (endStr) {
                                        paystagesA[0].End_Datetime = endStr;
                                    }
                                    paystagesA[0].Operation_ID = creator;
                                    paystagesA[0].Operation_Datetime = now;
                                    await generalApi.generalSaveByRequestBody({
                                        Data: { Modify: { supply_order_paystages: paystagesA } }
                                    });
                                }
                            }
                        } catch (e) { /* ignore */ }
                    }
                    this.getList();
                }
                this.$message.success(nextStatus === '11' ? '买卖双方确认，合同生效' : '买方已确认合同');
            } catch (e) {
                console.error(e);
                this.$message.error('买方确认失败，请稍后重试');
            }
        },
        // 根据单位流水号返回单位中文名
        getUnitText(serial) {
            const s = String(serial || '').trim();
            if (!s) return '';
            return this.unitMap[s] || s;
        },
        // 格式化原供应单地址
        formatSupplyAddress(s) {
            if (!s) return '';
            const p = s.ProvinceNumber || '';
            const c = s.CityNumber || '';
            const d = s.CountyNumber || '';
            const a = s.Detailed_Address || '';
            return `${p}${c}${d}${a}`;
        },
        // 剩余量（兼容无该字段的情况）
        getRemainQuantity(s) {
            if (!s) return '';
            if (s.Remain_Quantity !== undefined && s.Remain_Quantity !== null) return s.Remain_Quantity;
            const t = Number(s.Total_Quantity || 0);
            const sold = Number(s.Sales_Quantity || 0);
            return t - sold;
        },
        // 打开确认合同选择弹窗
        openContractDialog(row) {
            this.currentContractRow = row || null;
            this.dialogContractVisible = true;
        },
        // 线上签约
        startOnlineSigning() {
            this.dialogContractVisible = false;
            const row = this.currentContractRow;
            if (!row) return;
            // TODO: 在此发起线上签约流程或跳转到签约页面
            this.$message.success('已选择：线上签约');
        },
        // 线下签约
        startOfflineSigning() {
            this.dialogContractVisible = false;
            const row = this.currentContractRow;
            if (!row) return;
            // TODO: 在此记录线下签约意向或跳转到线下流程页面
            this.$message.success('已选择：线下签约');
        },
        // 设置阶段开始/结束时间
        async upsertStageStart(orderSerial, stageName) {
            if (!orderSerial || !stageName) return;
            try {
                // 1) 用预设 SQL（supply_payment_stages）定位目标阶段（按报价阶段排序）
                const sqlArr = await generalApi.generalQueryBySQLSerialNumber({
                    SQLSerialNumber: 'supply_payment_stages',
                    Condition: utf8ToBase64(String(orderSerial || '')),
                    ExtensionCondition: ''
                });
                const rows = Array.isArray(sqlArr) ? sqlArr : [];
                const light = rows.find(r => String(r.Stage_Name || '').trim() === String(stageName || '').trim());
                if (!light) {
                    // 未定位到阶段，不新增，记操作日志
                    await generalApi.generalSaveByRequestBody({
                        Data: {
                            Add: {
                                base_operation_log: [{
                                    Operation_Type: '0',
                                    Operation_Path: getRelativePath(),
                                    Operation_Description: `未定位到阶段：${stageName}`,
                                    Operation_Main: JSON.stringify({ Supply_Order_SerialNumber: orderSerial, Stage_Name: stageName }),
                                    Operation_Interface: 'generalQueryBySQLSerialNumber',
                                    Operation_IP: getIpAddress()
                                }]
                            }
                        }
                    });
                    return;
                }

                // 2) WithOriginal 回查“订单阶段原始行”，只做修改不新增
                let stageRow = null;
                if (light.Supply_Order_Paystages_SerialNumber) {
                    const originalArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'supply_order_paystages',
                        Condition: `Supply_Order_Paystages_SerialNumber='${String(light.Supply_Order_Paystages_SerialNumber).replace(/'/g, "''")}'`
                    });
                    stageRow = Array.isArray(originalArr) ? originalArr[0] : (originalArr && originalArr.Data && originalArr.Data[0]);
                }
                if (!stageRow) {
                    // 兼容少量历史数据：用订单号 + 报价阶段主键回查
                    const condFallback = `Supply_Order_SerialNumber='${String(orderSerial).replace(/'/g, "''")}' AND Supply_Unit_Price_Staged_Payment_SerialNumber='${String(light.Supply_Unit_Price_Staged_Payment_SerialNumber||'').replace(/'/g, "''")}'`;
                    const fbArr = await generalApi.generalQueryByTableNameWithOriginal({ Data: 'supply_order_paystages', Condition: condFallback });
                    stageRow = Array.isArray(fbArr) ? fbArr[0] : (fbArr && fbArr.Data && fbArr.Data[0]);
                }
                if (!stageRow) {
                    // 仍未找到则只写日志并返回
                    await generalApi.generalSaveByRequestBody({
                        Data: {
                            Add: {
                                base_operation_log: [{
                                    Operation_Type: '0',
                                    Operation_Path: getRelativePath(),
                                    Operation_Description: `未找到订单阶段原始行：${stageName}`,
                                    Operation_Main: JSON.stringify({ Supply_Order_SerialNumber: orderSerial, Stage_Name: stageName }),
                                    Operation_Interface: 'generalQueryByTableNameWithOriginal',
                                    Operation_IP: getIpAddress()
                                }]
                            }
                        }
                    });
                    return;
                }

                // 3) 以报价阶段主键查询 Pay_Time（天），用于计算结束时间
                let payDays = 0;
                if (light.Supply_Unit_Price_Staged_Payment_SerialNumber) {
                    const planArr = await generalApi.generalQueryByTableNameWithOriginal({
                        Data: 'supply_unitprice_staged_payment',
                        Condition: `Supply_Unit_Price_Staged_Payment_SerialNumber='${String(light.Supply_Unit_Price_Staged_Payment_SerialNumber).replace(/'/g, "''")}'`
                    });
                    const plan = Array.isArray(planArr) ? planArr[0] : (planArr && planArr.Data && planArr.Data[0]);
                    payDays = Number(plan && plan.Pay_Time) || 0;
                }

                const nowDate = new Date();
                const beginStr = getYMDHMSDate(nowDate);
                let endStr = '';
                if (payDays > 0) {
                    const calc = new Date(nowDate.getTime() + payDays * 24 * 3600 * 1000);
                    endStr = getYMDHMSDate(calc);
                }

                const creator = $.cookie('user') || $.cookie('enterprise') || '';
                stageRow.Start_Datetime = stageRow.Start_Datetime && String(stageRow.Start_Datetime).trim() ? stageRow.Start_Datetime : beginStr;
                if (endStr && (!stageRow.End_Datetime || !String(stageRow.End_Datetime).trim())) {
                    stageRow.End_Datetime = endStr;
                }
                stageRow.Operation_ID = creator;
                stageRow.Operation_Datetime = beginStr;
                // 保持报价阶段主键一致
                if (light.Supply_Unit_Price_Staged_Payment_SerialNumber) {
                    stageRow.Supply_Unit_Price_Staged_Payment_SerialNumber = light.Supply_Unit_Price_Staged_Payment_SerialNumber;
                }

                // 4) 仅修改原始行，避免新增任何 SUSP* 重复行
                await generalApi.generalSaveByRequestBody({
                    Data: {
                        Modify: {
                            supply_order_paystages: [stageRow]
                        },
                        Add: {
                            base_operation_log: [{
                                Operation_Type: '0',
                                Operation_Path: getRelativePath(),
                                Operation_Description: `设置阶段开始时间：${stageName}`,
                                Operation_Main: JSON.stringify({ Supply_Order_SerialNumber: orderSerial, Stage_Name: stageName, Start_Datetime: stageRow.Start_Datetime, End_Datetime: stageRow.End_Datetime }),
                                Operation_Interface: 'generalSaveByRequestBody',
                                Operation_IP: getIpAddress()
                            }]
                        }
                    }
                });
            } catch (e) {
                console.warn('设置阶段开始失败', e);
            }
        },
        // 订单收付/发收汇总（来自 supply_order 字段）
        getOrderSummary(row) {
            const toNum = v => {
                if (v === null || v === undefined || v === '') return 0;
                const n = Number(v);
                return isNaN(n) ? 0 : n;
            };
            return [
                {
                    label: '付款',
                    plan: toNum(row.Amount),
                    done: toNum(row.Paid_Amount),
                    remain: toNum(row.Remain_Amount)
                },
                {
                    label: '收款',
                    plan: toNum(row.Amount),
                    done: toNum(row.Collection_Amount),
                    remain: toNum(row.Unamount)
                },
                {
                    label: '发货',
                    plan: toNum(row.Quantity),
                    done: toNum(row.Delivery_Quantity),
                    remain: toNum(row.Undelivery_Quantity)
                },
                {
                    label: '收货',
                    plan: toNum(row.Quantity),
                    done: toNum(row.Receipt_Quantity),
                    remain: toNum(row.Unreceipt_Quantity)
                }
            ];
        },
       
    }
});
